package com.study.sbsummary.config.database;

import com.study.sbsummary.config.database.shadow.ShadowInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
@Slf4j
public class SqlMetadataConfig {
    //每隔多久重新load 每个session里的表元数据，当前为30分钟
    private static final long LOAD_METADATA_DURATION = 30 * 60 * 1000;

    @Autowired
    private InterceptorConfig interceptorConfig;

    @Autowired
    private ShadowInterceptor shadowInterceptor;

    @Autowired
    private Map<String, SqlSessionFactory> sqlSessionFactories;

    //    @Scheduled(fixedRate = LOAD_METADATA_DURATION)
    public void startLoadMetadata() {
        log.info("startLoadMetadata...");
        if (sqlSessionFactories == null || !shadowInterceptor.isSupportOnlineTest() || shadowInterceptor.isShadowDatabase()) {
            return;
        }
        loadMetadata();
        /**
         new Thread(() -> {
         log.info("*******starting to load database metadata thread*******");
         while (true) {
         loadMetadata();
         ThreadUtil.sleep(LOAD_METADATA_DURATION);
         }
         }, "Sql-Metadata-Loader").start();
         */
    }

    private void loadMetadata() {
        for (Map.Entry<String, SqlSessionFactory> entry : sqlSessionFactories.entrySet()) {
            log.info("begin to load metadata for session {}", entry.getKey());
            interceptorConfig.loadMetadata(entry.getKey(), entry.getValue());
        }
    }
}
